//
//  YBForgetPwdView.swift
//  Moonlight
//
//  Created by Penlon Kim on 2023/6/7.
//  Copyright © 2023 Moonlight Game Streaming Project. All rights reserved.
//

import UIKit
import SnapKit

protocol YBForgetPwdViewDelegate: NSObjectProtocol {
    func forgetPwdViewGetCode()
    func forgetPwdViewDidClick(_ btnType: YBForgetPwdView.BtnType)
    func forgetPwdViewInput(_ inputType: YBForgetPwdView.InputType, content: String)
}

class YBForgetPwdView: UIView {
    
    enum BtnType {
        case confirm
        case login
        case register
    }
    
    enum InputType: Int {
        case phone = 2000
        case code
        case pwd
        case newPwd
        
        var style: (icon: String, des: String) {
            switch self {
            case .phone: return ("icon_login_phone", "请输入手机号")
            case .code: return ("icon_login_code", "请输入手机验证码")
            case .pwd: return ("icon_login_pwd", "请输入新密码")
            case .newPwd: return ("icon_login_pwd", "请重复输入新密码")
            }
        }
    }
    
    weak var delegate: YBForgetPwdViewDelegate?
    
    private var countdowning = false {
        didSet {
            getCodeBtn.isUserInteractionEnabled = !countdowning
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubviews([titleLabel, welcomeLabel, confirmBtn, loginBtn, registerBtn, tipsTextView, checkBtn])
        
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(kNavigationBarHeight-offset15)
            make.height.equalTo(22)
        }
        
        welcomeLabel.snp.makeConstraints { make in
            make.left.equalTo(25)
            make.top.equalTo(titleLabel.snp.bottom).offset(offset40)
            make.height.equalTo(28)
        }
        
        self.reloadLoginInputView()
        
        if let codeTextField = self.viewWithTag(InputType.code.rawValue) {
            codeTextField.addSubview(getCodeBtn)
            codeTextField.bringSubviewToFront(getCodeBtn)
            getCodeBtn.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.right.equalTo(-17)
            }
            
            let line = UIView(color: kRGBColor(191, 190, 190))
            codeTextField.addSubview(line)
            line.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.right.equalTo(getCodeBtn.snp.left).offset(-10)
                make.size.equalTo(CGSizeMake(1, 16))
            }
        }
        
        if let newPwdTextField = self.viewWithTag(InputType.newPwd.rawValue) {
            let pwdTipLabel = self.bk_addLabel(text: "密码必须由数字和字母6-10位数字组合成", font: .systemFont(ofSize: 12), bgColor: .clear, textColor: kRGBColor(234, 58, 58))
            self.addSubview(pwdTipLabel)
            pwdTipLabel.snp.makeConstraints { make in
                make.left.equalTo(newPwdTextField.snp.left)
                make.top.equalTo(newPwdTextField.snp.bottom).offset(10)
            }
            
            confirmBtn.snp.makeConstraints { make in
                make.top.equalTo(newPwdTextField.snp.bottom).offset(offset70)
                make.left.right.equalToSuperview().inset(25)
                make.height.equalTo(42)
                make.centerX.equalToSuperview()
            }
        }
        
        loginBtn.snp.makeConstraints { make in
            make.top.equalTo(confirmBtn.snp.bottom).offset(offset30)
            make.left.right.equalToSuperview().inset(25)
            make.height.equalTo(42)
            make.centerX.equalToSuperview()
        }
        
        registerBtn.snp.makeConstraints { make in
            make.right.equalTo(-25)
            make.top.equalTo(loginBtn.snp.bottom).offset(10)
        }
        
        checkBtn.snp.makeConstraints { make in
            make.size.equalTo(14)
            make.left.equalTo(25)
            make.top.equalTo(registerBtn.snp.bottom).offset(offset30)
            make.bottom.lessThanOrEqualTo(-kBottomSafeHeight-offset15)
        }
        
        tipsTextView.snp.makeConstraints { make in
            make.centerY.equalTo(checkBtn)
            make.left.equalTo(checkBtn.snp.right).offset(7)
            make.right.equalTo(-25)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - lazy
    private lazy var titleLabel = self.bk_addLabel(text: "忘记密码", font: .systemFont(ofSize: 16, weight: .bold), bgColor: .clear, textColor: .lightBlackDarkWhite, align: .center)
    
    private lazy var welcomeLabel = self.bk_addLabel(text: "重置登录密码", font: .systemFont(ofSize: 20, weight: .medium), bgColor: .clear, textColor: .lightBlack58DarkLight230, align: .center)
    
    private lazy var confirmBtn: UIButton = {
        let btn = self.bk_addButton(type: .custom, title: "确认", font: .systemFont(ofSize: 18), bgColor: ColorDef.dark27, titleColor: .white, radius: 8)
        btn.bk_addShadowStyleWith(cornerRadius: 8, corners: .allCorners)
        btn.bk_addTarget { [unowned self] sender in
            self.delegate?.forgetPwdViewDidClick(.confirm)
        }
        return btn
    }()
    
    private lazy var loginBtn: UIButton = {
        let btn = self.bk_addButton(type: .custom, title: "去登录", font: .systemFont(ofSize: 18), bgColor: ColorDef.dark27, titleColor: .white, radius: 8)
        btn.bk_addTarget { [unowned self] sender in
            self.delegate?.forgetPwdViewDidClick(.login)
        }
        return btn
    }()
    
    private lazy var getCodeBtn: UIButton = {
        let btn = self.bk_addButton(type: .custom, title: "获取验证码", font: .systemFont(ofSize: 14, weight: .medium), bgColor: .clear, titleColor: kRGBColor(46, 143, 255))
        btn.bk_addTarget { [unowned self] (sender) in
            self.delegate?.forgetPwdViewGetCode()
        }
        return btn
    }()
    
    private lazy var registerBtn: UIButton = {
        let btn = self.bk_addButton(title: "立即注册", font: .systemFont(ofSize: 12), bgColor: .clear, titleColor: .lightBlack58DarkLight230)
        btn.bk_setEnlargeEdge(10)
        btn.bk_addTarget { [unowned self] sender in
            self.delegate?.forgetPwdViewDidClick(.register)
        }
        return btn
    }()
    
    lazy var checkBtn: UIButton = {
        let btn = self.bk_addImgSelectButton(iconNormal: "icon_check_normal", iconSelect: "icon_check_select")
        btn.bk_setEnlargeEdge(10)
        btn.bk_addTarget { [unowned self] (sender) in
            sender.isSelected = !sender.isSelected
        }
        return btn
    }()
    
    /// 用户协议
    private lazy var tipsTextView: UITextView = {
        let textV = UITextView()
        textV.backgroundColor = .clear
        textV.textAlignment = .left
        textV.isEditable = false
        textV.isScrollEnabled = false
        textV.linkTextAttributes = [.foregroundColor: UIColor.lightBlack58DarkLight230]
        textV.attributedText = self.reloadTipsTextAttr()
        return textV
    }()
    
}

// MARK: - Public
extension YBForgetPwdView {
    
    /// 获取验证码时间倒计时
    func gcdWithGetCode(need create: Bool) {
        if countdowning {
            // 当前正在倒计时, 直接return, 防止重复调用
            return
        }
        
        CountdownManager.sharedInstance().start(reuseId: "ForgetPwd", count: 60, create: create) { [weak self] (second) in
            if second <= 0 {
                self?.countdowning = false
                self?.getCodeBtn.setTitle("获取验证码", for: .normal)
            } else {
                self?.countdowning = true
                self?.getCodeBtn.setTitle("\(second)s后重新获取", for: .normal)
            }
        }
    }
    
}

// MARK: - Private
extension YBForgetPwdView {
    
    private func reloadLoginInputView() {
        self.reloadLoginInputs(by: [.phone, .code, .pwd, .newPwd])
    }
    
    private func reloadLoginInputs(by types: [InputType]) {
        var tmpView: UIView?
        for type in types {
            let tf = UITextField()
            tf.borderStyle = .none
            tf.backgroundColor = .lightGray250Dark33
            tf.bk_addPlaceholder(type.style.des, color: kRGBColor(144, 147, 147), font: .systemFont(ofSize: 14))
            tf.bk_addIconForLeftView(img: UIImage(named: type.style.icon), viewSize: CGSizeMake(36, 20), imgSize: CGSizeMake(20, 20))
            tf.tag = type.rawValue
            tf.textColor = .lightBlack58DarkLight230
            tf.font = .systemFont(ofSize: 14)
            
            self.addSubview(tf)
            tf.bk_addStyleWith(cornerRadius: 48/2, corners: .allCorners)
            tf.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview().inset(25)
                make.height.equalTo(48)
                make.centerX.equalToSuperview()
                if tmpView == nil {
                    make.top.equalTo(welcomeLabel.snp.bottom).offset(offset45)
                } else {
                    make.top.equalTo(tmpView!.snp.bottom).offset(offset30)
                }
            }
            
            tf.bk_addTarget { [unowned self] (textF) in
                self.delegate?.forgetPwdViewInput(type, content: textF.text ?? "")
            }
            tmpView = tf
        }
    }
    
    private func reloadTipsTextAttr() -> NSMutableAttributedString {
        let str: NSString = "我已阅读并同意《酷卡云服务协议》" as NSString
        let attrText = NSMutableAttributedString(string: str as String)
        let range0 = str.range(of: "我已阅读并同意")
        let range1 = str.range(of: "《酷卡云服务协议》")
        attrText.addAttributes([.foregroundColor: UIColor.lightBlack58DarkLight230, .link: "agreement://", .font: UIFont.systemFont(ofSize: 12)], range: range1)
        attrText.addAttributes([.foregroundColor: ColorDef.gray153, .font: UIFont.systemFont(ofSize: 12)], range: range0)
        return attrText
    }
    
}
